const soundConfig = require('../configs/soundConfig');

class soundManager {
    constructor() {
        this.bgmID = null;
        this.effectID = null;
        this.init();
    }

    init() {
        let bgmNum = cc.sys.localStorage.getItem('bgm') || 0.99;
        let effectNum = cc.sys.localStorage.getItem('mp3') || 1.0;
        cc.audioEngine.setMusicVolume(bgmNum);
        cc.audioEngine.setEffectsVolume(effectNum);
    }

    loadSoundTexture() {
        ICPC.addOneLoad();
        cc.loader.loadResDir('public/sound', (error, resources, urls) => {
            if (error) {
                console.error('声音资源加载出错', error);
                return;
            }
            console.log('音乐加载完成', resources.length);
            ICPC.oneLoadOver();
        })
    }

    loadSoundId(soundKey) {
        let url = soundConfig[soundKey];
        return new Promise((resolve) => {
            cc.loader.loadRes(url, cc.AudioClip, function (err, clip) {
                if (err) {
                    console.error('错误的音频文件', url, soundKey, err);
                    return;
                }
                resolve(clip);
            });
        });
    }

    playerFreeBGM() {
        this.loadSoundId('freeBgm').then((clip) => {
            this.bgmID = cc.audioEngine.playMusic(clip, true);
        });
    }

    playerGameBGM() {
        this.loadSoundId('fightBgm').then((clip) => {
            this.bgmID = cc.audioEngine.playMusic(clip, true);
        });
    }

    privatePlayEffect(key) {
        this.loadSoundId(key).then((clip) => {
            cc.audioEngine.playEffect(clip, false);
        })
    }

    playBullet() {
        //太吵了
        return;
        this.privatePlayEffect('biu');
    }

    playBoom() {
        this.privatePlayEffect('boom');
    }

    playBt() {
        this.privatePlayEffect('bt');
    }

    getBGMVoice() {
        return cc.audioEngine.getMusicVolume();
    }

    getEFFECTVoice() {
        return cc.audioEngine.getEffectsVolume();
    }

    setBGMVoice(fNum) {
        cc.audioEngine.setMusicVolume(fNum);
        cc.sys.localStorage.setItem('bgm', fNum);
    }

    setEFFECTVoice(fNum) {
        cc.audioEngine.setEffectsVolume(fNum);
        cc.sys.localStorage.setItem('mp3', fNum);
    }
}

module.exports = soundManager;